<?php

namespace Biz\model\activity;

use Doraemon\model\Admin\BeerUsUser;


class BizProjectModel extends BizProjectBaseModel
{
    const _TABLE_NAME = 'biz_project';

    static array $foldKey = ['responsible','customer','project','process','contract','costs'];

    use BizProjectTrait;

    public static function getProcessList(array $condition): array
    {
        $response = [];
        $responsibilityCondition = $condition['responsibility'] ?? [];
        unset($condition['responsibility']);
        $list = self::dataSelect( self::statusCondition() + $condition);
        $ids = $list ? array_column($list, 'id') : [];
        $responsible = BizProjectResponsibilityModel::findAdminByProjectId($ids);
        $admin_ids = BizProjectResponsibilityModel::afterFindAdmin();
        BeerUsUser::getNameByUsername($admin_ids);
        $project = [];
        $count = count($ids);
        $amount = 0;
        foreach ($list as $item) {
            $pm_extra = empty($item['pm_extra']) ? [] : json_decode($item['pm_extra'], true);
            $extra = [];
            foreach ($pm_extra as $v) {
                $extra[$v['pm']] = (float)$v['value'] * (float)$item['project_money'];
            }
            $project[$item['id']] = [
                'project_money' => $item['project_money'],
                'pm_extra' => $extra,
            ];
            $amount += $item['project_money'];
        }

        $projectCounter = [];
        $projectAmountCounter = [];
        $nameMap = array_flip(BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_NAME_MAP);
        foreach ($responsible as $projectId => $item) {
            $admins = [];
            foreach ($item as $name => $admin) {
                $name = $nameMap[$name];
                if (empty($responsibilityCondition) || in_array($name, $responsibilityCondition)) {
                    $admins = array_merge($admins, $admin);
                }
            }
            $admins = array_unique($admins);
            $projectItem = $project[$projectId];
            foreach ($admins as $admin) {
                $tempAmount = $projectItem['pm_extra'][$admin] ?? $projectItem['project_money'];
                $projectCounter[$admin] = isset($projectCounter[$admin]) ? ++$projectCounter[$admin] : 1;
                $projectAmountCounter[$admin] = isset($projectAmountCounter[$admin]) ? $projectAmountCounter[$admin] + $tempAmount : $tempAmount;
                $response[$admin] = [
                    'responsibility' => BeerUsUser::afterGetRowsMap($admin),
                    'num' => $projectCounter[$admin],
                    'amount' => number_format($projectAmountCounter[$admin], 2),
                ];
            }
        }
        return compact('amount', 'response', 'count');
    }

    public static function getAdmList(array $condition): array
    {
        $response = [];
        $list = self::dataSelect( self::statusCondition() + $condition);
        $ids = $list ? array_column($list, 'id') : [];
        $project_category_map = BizProjectPRelationIdsModel::getProjectRelationIds($ids);
        $category = BizProjectCategoryModel::adminNameLevelOptions();
        $responsible = BizProjectResponsibilityModel::findAdminByProjectId($ids);
        $admin_ids = BizProjectResponsibilityModel::afterFindAdmin();
        BeerUsUser::getNameByUsername($admin_ids);
        if ($list) {
            foreach ($list as $v) {
                $tempResponsible = $responsible[$v['id']] ?? [];
                $tempProjectCategory = $project_category_map[$v['id']] ?? [];
                if ($tempProjectCategory) {
                    $temp = [];
                    foreach ($tempProjectCategory as $categoryId) {
                        $temp[] = $category[$categoryId];
                    }
                    $v['customer_category'] = $temp;
                } else {
                    $v['customer_category'] = $category[$v['customer_category']];
                }
                $v['created_at_date'] = $v['created_at'];
                $v['responsible_seller'] = BeerUsUser::afterGetRowsMap($tempResponsible['seller'] ?? []);
                $v['responsible_pm'] = BeerUsUser::afterGetRowsMap($tempResponsible['pm'] ?? []);
                $v['responsible_planner'] = BeerUsUser::afterGetRowsMap($tempResponsible['planner'] ?? []);
                $v['responsible_medium'] = BeerUsUser::afterGetRowsMap($tempResponsible['medium'] ?? []);
                $v['responsible_mcn'] = BeerUsUser::afterGetRowsMap($tempResponsible['mcn'] ?? []);
                $v['responsible_finance'] = BeerUsUser::afterGetRowsMap($tempResponsible['finance'] ?? []);
                $v['responsible_legal'] = BeerUsUser::afterGetRowsMap($tempResponsible['legal'] ?? []);
                $v['admin'] = BeerUsUser::afterGetRowsMap(current($tempResponsible['owner'] ?? []));
                $v['project_money_format'] = number_format(floatval($v['project_money']), 2);
                $v['project_time'] = date("Y-m-d", strtotime($v['project_start_date'])) . "~" . date("Y-m-d", strtotime($v['project_end_date']));
                $v['responsible'] = $tempResponsible;
                $response[] = $v;
            }
        }
        return $response;
    }

    public static function getAdmInfo($id): array
    {
        $info = $id ? self::get("*", ['id' => $id]) : [];


        return $info ? self::formatAdmInfo($info) : [];
    }

    public static function formatAdmInfo($info): array
    {
        $format = [];
        foreach ($info as $key => $v) {
            $keyArr = explode('_', $key);
            $pre = current($keyArr);
            if (in_array($pre, self::$foldKey) && count($keyArr) > 1) {
                $format[$pre][implode("_", array_slice($keyArr, 1))] = $v;
            } else {
                $format[$key] = $v;
            }
        }

        if (!empty($info['project_rebates'])) {
            $format['rebates'] = json_decode($info['project_rebates'], true);
        }
        if (!empty($info['project_contract'])) {
            $format['contracts'] = json_decode($info['project_contract'], true);
        }
        if (!empty($info['pm_extra'])) {
            $format['pms'] = json_decode($info['pm_extra'], true);
        }
        //
        if (!empty($format['customer'])) {
            $customer = BizProjectCustomerModel::get('*', ['id' => $format['customer']['name']]);
            if ($customer) {
                $format['customer']['area'] = $customer['customer_area'];
                $format['customer']['area_code'] = $customer['customer_area_code'];
                $format['customer']['intro'] = $customer['customer_intro'];
                $format['customer']['features'] = $customer['customer_features'];
            }
        }
        $relation = BizProjectPRelationIdsModel::getProjectRelationIds($info['id']);
        if ($relation) {
            $format['customer']['category'] = $relation;
        }
        $format['responsible'] = BizProjectResponsibilityModel::findAdminByProjectId($info['id']);
        if (empty($format['pms'])) {
            $format['pms'] = [];
            if (!empty($format['responsible']['pm'])) {
                foreach ($format['responsible']['pm'] as $pm) {
                    $format['pms'][] = [
                        'pm' => $pm,
                        'value' => '',
                    ];
                }
            }
        }
        if (!empty($format['project']['mcn_uid'])) {
            $rs = BizProjectMcnModel::dataSelect(['project_id' => $info['id']] + BizProjectMcnModel::statusCondition());
            $uids = array_column($rs, 'uid');
            $profiles = \Doraemon\service\UserPortrait\UserPortraitApi::request($uids, ['fans_num','product_level','nick','user_business_layer']);
            $format['mcn'] = [];
            if ($rs) {
                foreach ($rs as $v) {
                    $profile = $profiles[$v['uid']] ?? [];
                    $format['mcn'][] = [
                        $v['uid'],
                        $profile['nick'] ?? '-',
                        $profile['fans_num'] ?? 0,
                        $profile['product_level'] ?? '-',
                        $profile['user_business_layer'] ?? '-',
                    ];
                }
            }
        }
        return $format;
    }

    public static function formatAdmSaveInfo($info): array
    {
        $format = [];
        $format['project']['project_contract'] = '';
        foreach ($info as $key => $v) {
            if (in_array($key, self::$foldKey)) {
                foreach ($v as $k => $param) {
                    $format[$key][implode("_", [$key, $k])] = self::formatMultiParam($param);
                }
            } elseif ($key == 'pms') {
                $temp = [];
                $pm = [];
                foreach ($v as $event) {
                    if ($event['_remove_']) {
                        continue;
                    }
                    unset($event['_remove_']);
                    $temp[] = $event;
                    $pm[] = $event['pm'];
                }
                $format['responsible']['responsible_pm'] = implode(',', $pm);
                $format['responsible']['pm_extra'] = $temp ? json_encode(array_values($temp), JSON_UNESCAPED_UNICODE) : '';
            }elseif ($key == 'contracts') {
                $temp = [];
                foreach ($v as $event) {
                    if ($event['_remove_']) {
                        continue;
                    }
                    unset($event['_remove_']);
                    $temp[] = $event;
                }
                $format['project']['project_contract'] = $temp ? json_encode(array_values($temp), JSON_UNESCAPED_UNICODE) : '';
            } elseif ($key == 'rebates') {
                $temp = [];
                foreach ($v as $event) {
                    if ($event['_remove_']) {
                        continue;
                    }
                    unset($event['_remove_']);
                    $temp[] = $event;
                }
                $format['project_rebates']['project_rebates'] = $temp ? json_encode(array_values($temp), JSON_UNESCAPED_UNICODE) : '';
            }
        }
        return $format;
    }
}
